import SwiftUI
import AppKit

@main
struct MenuBarCalendarNewApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        // 对于菜单栏应用，我们不需要主窗口
        Settings {
            EmptyView()
        }
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    var statusItem: NSStatusItem?
    var popover: NSPopover?
    
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // 创建状态栏项
        statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
        
        // 设置状态栏项的按钮
        if let button = statusItem?.button {
            button.image = generateCalendarIcon()
            button.imagePosition = .imageLeft
            button.action = #selector(togglePopover)
            button.sendAction(on: [.leftMouseUp, .rightMouseUp])
        }
        
        // 创建弹出视图
        popover = NSPopover()
        popover?.contentSize = NSSize(width: 280, height: 380)
        popover?.behavior = .transient
        popover?.appearance = NSAppearance(named: .vibrantLight)
        popover?.contentViewController = NSHostingController(rootView: CalendarView())
        
        // 设置毛玻璃效果
        if let contentView = popover?.contentViewController?.view {
            contentView.wantsLayer = true
            contentView.layer?.cornerRadius = 12
            contentView.layer?.masksToBounds = true
        }
        
        // 隐藏dock图标
        NSApp.setActivationPolicy(.accessory)
    }
    
    @objc func togglePopover() {
        if let event = NSApp.currentEvent {
            if event.type == .rightMouseUp {
                showMenu()
            } else {
                if let popover = popover, let button = statusItem?.button {
                    if popover.isShown {
                        popover.performClose(nil)
                    } else {
                        // 确保应用激活以显示 popover
                        NSApp.activate(ignoringOtherApps: true)
                        popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
                    }
                }
            }
        }
    }
    
    @objc func showMenu() {
        let menu = NSMenu()
        
        let quitItem = NSMenuItem(title: "退出", action: #selector(quitApp), keyEquivalent: "q")
        quitItem.target = self
        menu.addItem(quitItem)
        
        statusItem?.menu = menu
        statusItem?.button?.performClick(nil)
        statusItem?.menu = nil
    }
    
    @objc func quitApp() {
        NSApplication.shared.terminate(nil)
    }
    
    func applicationWillTerminate(_ aNotification: Notification) {
        // 应用终止时清理资源
    }
    
    /// 生成日历图标（带有日期的图像）
    private func generateCalendarIcon() -> NSImage {
        let date = Date()
        let calendar = Calendar.current
        let day = calendar.component(.day, from: date)
        
        // 创建一个NSImage对象
        let size = NSSize(width: 22, height: 22)
        let image = NSImage(size: size)
        
        // 在图像上下文中绘制
        image.lockFocus()
        
        // 设置背景色为透明
        NSColor.clear.set()
        NSRect(origin: .zero, size: size).fill()
        
        // 绘制日历图标轮廓（更美观的设计）
        let bezierPath = NSBezierPath()
        
        // 日历外框
        bezierPath.appendRoundedRect(NSRect(x: 2, y: 2, width: 18, height: 18), xRadius: 2, yRadius: 2)
        
        // 顶部的挂环
        bezierPath.move(to: NSPoint(x: 6, y: 20))
        bezierPath.line(to: NSPoint(x: 6, y: 18))
        bezierPath.line(to: NSPoint(x: 16, y: 18))
        bezierPath.line(to: NSPoint(x: 16, y: 20))
        
        // 星期几的分隔线
        bezierPath.move(to: NSPoint(x: 2, y: 15))
        bezierPath.line(to: NSPoint(x: 20, y: 15))
        
        NSColor.black.setStroke()
        bezierPath.lineWidth = 1.2
        bezierPath.stroke()
        
        // 绘制日期数字
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center
        
        let attributes: [NSAttributedString.Key: Any] = [
            .font: NSFont.systemFont(ofSize: 11, weight: .semibold),
            .foregroundColor: NSColor.black,
            .paragraphStyle: paragraphStyle
        ]
        
        let dayString = "\(day)"
        let textSize = dayString.size(withAttributes: attributes)
        let textRect = NSRect(
            x: (size.width - textSize.width) / 2,
            y: (size.height - textSize.height) / 2 - 2,
            width: textSize.width,
            height: textSize.height
        )
        
        dayString.draw(in: textRect, withAttributes: attributes)
        
        image.unlockFocus()
        
        return image
    }
}